package cn.iocoder.yudao.module.wms.controller.admin.index;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.wms.controller.admin.customer.vo.CustomerRespVO;
import cn.iocoder.yudao.module.wms.controller.admin.index.vo.BaseDataVO;
import cn.iocoder.yudao.module.wms.controller.admin.index.vo.WeatherFetcherVO;
import cn.iocoder.yudao.module.wms.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.wms.service.index.IndexService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "首页数据")
@RestController
@RequestMapping("/wms/index")
@Validated
public class indexController {
    @Resource
    IndexService indexService;
    private static final String API_URL = "https://api.openweathermap.org/data/2.5/weather";
    private static final String API_KEY = "f6a70f20376ef3e9d66f77125c3b1e54";

    private static final Map<String, String> DESCRIPTION_MAP = new HashMap<>();

    static {
        DESCRIPTION_MAP.put("clear sky", "晴朗");
        DESCRIPTION_MAP.put("few clouds", "少云");
        DESCRIPTION_MAP.put("scattered clouds", "分散的云");
        DESCRIPTION_MAP.put("broken clouds", "多云");
        DESCRIPTION_MAP.put("overcast clouds", "阴天");
        DESCRIPTION_MAP.put("light rain", "小雨");
        DESCRIPTION_MAP.put("moderate rain", "中雨");
        DESCRIPTION_MAP.put("heavy intensity rain", "大雨");
        DESCRIPTION_MAP.put("thunderstorm", "雷暴");
        DESCRIPTION_MAP.put("snow", "下雪");
        DESCRIPTION_MAP.put("mist", "薄雾");
        // 添加更多描述...
    }

    public static String translate(String description) {
        return DESCRIPTION_MAP.getOrDefault(description.toLowerCase(), "未知天气");
    }

    @GetMapping("/getWeatherFetcher")
    @Operation(summary = "获取天气")
    public CommonResult<WeatherFetcherVO> getWeatherFetcher() {
        try {

            // 构建请求 URL
            String city = "jiaxin";
            String country = "cn";
//            String urlString = String.format("%s?q=%s,%s&appid=%s&units=metric", API_URL, city, country, API_KEY);
            String urlString="https://api.openweathermap.org/data/2.5/weather?q=jiaxin,cn&appid=f6a70f20376ef3e9d66f77125c3b1e54&units=metric";
            URL url = new URL(urlString);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 检查响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect();

                // 解析 JSON 响应
                JsonObject jsonResponse = JsonParser.parseString(content.toString()).getAsJsonObject();
                System.out.println("Weather Data: " + jsonResponse);

                // 提取和打印一些具体信息
                JsonObject main = jsonResponse.getAsJsonObject("main");
                WeatherFetcherVO weatherFetcherVO=new WeatherFetcherVO()
                        .setTemp(main.get("temp").getAsDouble());

                JsonArray weatherArray = jsonResponse.getAsJsonArray("weather");
                if (weatherArray.size() > 0) {
                    JsonObject weatherObject = weatherArray.get(0).getAsJsonObject();
                    weatherFetcherVO.setDescription(translate(weatherObject.get("description").getAsString()));
                } else {
                }


                return success(weatherFetcherVO);
            } else {
                System.out.println("GET request failed. Response code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success(new WeatherFetcherVO());
    }
    @GetMapping("/getStock")
    @Operation(summary = "获取存货")
    public CommonResult<List<BaseDataVO>> getStock() {
        return success(indexService.getStock());
    }

    @GetMapping("/getOrder")
    @Operation(summary = "获取单户量")
    public CommonResult<List<BaseDataVO>> getOrder() {
        return success(indexService.getOrderList());
    }
    @GetMapping("/getMonth")
    public static CommonResult<List<String>> getRecent12Months() {
        List<String> months = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        LocalDate now = LocalDate.now();

        // 从当前月份开始，逐月向前推12个月
        for (int i = 0; i < 12; i++) {
            LocalDate date = now.minus(i, ChronoUnit.MONTHS);
            months.add(date.format(formatter));
        }

        // 如果需要按时间顺序排列，可以反转列表
        java.util.Collections.reverse(months);

        return success(months);
    }

    @GetMapping("/getLineOrderAll")
    public  CommonResult<List<BaseDataVO>> getLineOrder() {
        return success(indexService.getLineOrder(null));
    }

    @GetMapping("/getLineOrderSuccess")
    public  CommonResult<List<BaseDataVO>> getLineOrderSuccess() {
        return success(indexService.getLineOrder("0"));

    }
    /***
     * 获取当前登录用户的完成的表单数
     */
    @GetMapping("/getOrderByUser")
    public  CommonResult<Integer> getOrderByUser() {
        //获取当前登录用户
        Long id=WebFrameworkUtils.getLoginUserId();
        return success(indexService.getOrderByCreat("0",id));

    }

    /***
     * 获取当前登录用户的完成的表单数
     */
    @GetMapping("/getOrderAllByUser")
    public  CommonResult<Integer> getOrderAllByUser() {
        //获取当前登录用户
        Long id=WebFrameworkUtils.getLoginUserId();
        return success(indexService.getOrderByCreat(null,id));

    }

}


